import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Table,
  Divider,
  Tag,
  Tree,
  Row,
  Col,
  Button,
  Form,
  Modal,
  Input,
  Switch,
  Radio,
  Select,
  message,
  InputNumber,
} from 'antd';
import { connect } from 'dva';
import RenderButtom from '@/components/RenderButton';
import MenuTree from '@/components/MenuTree';
import SearchBox from '@/components/SearchBox'
import {
  fetchMenus,
  saveOrUpdateMenus,
  deleteMenus,
  btnMenuTree,
  searchMenus,
} from '@/services/menu';
import { formItemLayout, formatMenu } from '@/utils/utils'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const columns = [
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '菜单名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '路径',
    dataIndex: 'menuUrl',
    key: 'menuUrl',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => <span>{text == 0 ? '启用' : '锁定'}</span>,
  },
  {
    title: '是否是菜单',
    dataIndex: 'isMenu',
    key: 'isMenu',
    render: text => <span>{text == 0 ? '是' : '否'}</span>,
  },
];

const Permission = props => {
  const [visible, setVisible] = useState(false);
  const [keys, setKey] = useState(0);
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([])
  const [btnType, setBtnType] = useState('')
  const [rowKey, setRowKey] = useState([-1])
  const [menuId, setMenuId] = useState(null)
  const { getFieldDecorator, validateFieldsAndScroll, validateFields, resetFields } = props.form;
  const { inform } = props.role;

  useEffect(() => {
    init();
  }, [init]);

  const init = async (params) => {
    const res = await fetchMenus(params);
    setColData(res.data);
  };

  const updateMenus = async () => {
    const m = await btnMenuTree({
      token: JSON.parse(localStorage.getItem('user')).token || JSON.parse(sessionStorage.getItem('user')).token
    })

    props.dispatch({
      type: 'global/saveMenus',
      payload: {
        menus: formatMenu(m.data),
      },
    });
  }

  const removeMenu = async record => {
    const res = await deleteMenus({
      id: record.id,
    });
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setColData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  };
  const getOneMenu = async params => {
    const res = await searchMenus(params);
    setColData(res.data);
  };
  const handleBtns = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一个菜单！');
    switch (type) {
      // 新增
      case 1:  
        return handleStatus();
      case 3:      
        return handleStatus(record[0]);
      // 查询
      case 2:      
        return handleSearch();
      // 删除
      case 4:
        return removeMenu(record[0])
      default:
        break;
    }
    handleStatus()
  };

  const handleStatus = record => {
    setVisible(!visible);
    
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  };
  const selectMenu = async keys => {
    const res = await searchMenus({id: keys[0]});
    setKey(keys)
    if (!inform) {
      props.dispatch({
        type: 'role/changeModelState',
        payload: {
          inform: res.data[0]
        }
      })
    }
  };

  const onSubmit = e => {
    e.preventDefault();
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values, inform);
        let params = {}
        
        btnType == 1 ? 
        params = {
          ...values,
          status: !!values.status ? 0 : 1, // 是否启用
          parentId: keys.length == 0 ? 0 : keys[0], // 0为顶层菜单
          code: Math.random(), // 必填字段
        } :
        params = {
          ...inform,
          ...values,
          status: !!values.status ? 0 : 1, // 是否启用
          parentId: keys.length == 0 ? 0 : keys[0], // 0为顶层菜单
          id: values.id ? values.id : inform.id
        }
        
        saveOrUpdateMenus(params).then(() => {
          init();
          setRowKey(null)
          setVisible(!visible);
        });
      }
    });
  };

  // 查询表单
  const getFields = () => {
    return (
      <>
        <Col span={6}>
          <Form.Item label={`菜单名称`}>
            {getFieldDecorator('menuname', {
              })(<Select
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                onChange={val => setMenuId(val)}
              >
                {data && data.map(r => <Select.Option key={r.id} value={r.id}>{r.name}</Select.Option>)}
              </Select>)}        
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`菜单地址`}>
            {getFieldDecorator('menuurl', {
              })(<Input />)}        
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item label={`父菜单`}>
            {getFieldDecorator('parent', {
              })(<Select
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                onChange={val => setMenuId(val)}
              >
                {data && data.map(r => <Select.Option key={r.id} value={r.id}>{r.name}</Select.Option>)}
              </Select>)}        
          </Form.Item>
        </Col>
      </>
    );
  };

  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    validateFieldsAndScroll((err, val) => {
      init({
        id: val.menuname,
        menuUrl: val.menuurl,
        parentId: val.parent,
      });
    })
  };

  // 清空查询条件
  const handleReset = () => {
    resetFields();
    init()
  };
  
  const getInformation = (selectedKeys, e) => {
    console.log(selectedKeys, e)
  }

  const rowSelection = {
    type: 'radio',
    selectedRowKeys: rowKey,
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      setRowKey(selectedRowKeys)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtns} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id}
      />
      {/* 新增修改 */}
      <Modal visible={visible} onOk={onSubmit} onCancel={() => setVisible(!visible)} destroyOnClose>
        <Form {...formItemLayout}>
          <Form.Item label="排序">
            {getFieldDecorator('sort', {
              initialValue: inform && inform.sort,
            })(<InputNumber min={0} />)}
          </Form.Item>
          <Form.Item label="父菜单">
            {getFieldDecorator('parentId', {
              initialValue: inform && inform.parentId,
            })(
              <MenuTree
                defaultExpandAll={false}
                checkable={false}
                onSelect={selectMenu}
                defaultSelectedKeys={inform && [String(inform.parentId)]}
              />,
            )}
          </Form.Item>
          <Form.Item label="菜单名称">
            {getFieldDecorator('name', {
              initialValue: inform.id && inform.name,
              rules: [
                {
                  required: true,
                  message: '请输入菜单名称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="是否是菜单">
            {getFieldDecorator('isMenu', {
              initialValue: inform && inform.isMenu,
              rules: [
                {
                  required: true,
                },
              ],
            })(
              <Radio.Group>
                <Radio value={0}>是</Radio>
                <Radio value={1}>否</Radio>
              </Radio.Group>,
            )}
          </Form.Item>
          <Form.Item label="路径">
            {getFieldDecorator('menuUrl', {
              initialValue: inform.id && inform.menuUrl,
              rules: [
                {
                  required: true,
                  message: '请输入路径',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="图标">
            {getFieldDecorator('icon', {
              initialValue: inform && inform.icon,
              rules: [
                {
                  required: false,
                  message: '请输入图标',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('describes', {
              initialValue: inform && inform.describes,
              rules: [
                {
                  required: false,
                  message: '请输入描述',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: inform && !inform.status ? true : false,
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ global, role }) => ({
  global,
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(Permission));
